package com.demo.sender.email;

import com.demo.annotation.EmailChannel;
import com.demo.common.ResultData;
import com.demo.enums.EmailChannelEnum;
import com.demo.request.EmailSenderReq;
import com.demo.sender.email.config.EmailClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

/**
 * @author wangfengchen
 */
@EmailChannel(channel = EmailChannelEnum.JAVAMAIL)
@Component
@Slf4j
public class JavaEmailSender implements EmailSenderService {

  @Autowired(required = false)
  private JavaMailSender javaMailSender;
  @Autowired(required = false)
  private EmailClientConfig emailClientConfig;


  @Override
  public ResultData<Object> send(EmailSenderReq request) {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    try {
      // true表示支持复杂类型
      helper = new MimeMessageHelper(message, true, "utf-8");
      // 配置邮箱发送人
      helper.setFrom(emailClientConfig.getUsername());
      // 邮件的收件人
      helper.setTo(InternetAddress.parse(String.join(",", request.getToList())));
      // 邮件主题
      helper.setSubject(request.getSubject());
      // 邮件内容
      helper.setText(request.getBodyText());
      javaMailSender.send(helper.getMimeMessage());
      log.info("邮件发送成功");
      return ResultData.success();
    } catch (Exception e) {
      log.error("邮件发送失败，exception = {}", ExceptionUtils.getStackTrace(e));
      e.printStackTrace();
    }
    return ResultData.fail();
  }

  @Async
  @Override
  public ResultData<Object> sendAsync(EmailSenderReq request) {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    try {
      // true表示支持复杂类型
      helper = new MimeMessageHelper(message, true, "utf-8");
      // 配置邮箱发送人
      helper.setFrom(emailClientConfig.getUsername());
      // 邮件的收件人
      helper.setTo(InternetAddress.parse(String.join(",", request.getToList())));
      // 邮件主题
      helper.setSubject(request.getSubject());
      // 邮件内容
      helper.setText(request.getBodyText());
      javaMailSender.send(helper.getMimeMessage());
      log.info("邮件发送成功");
      return ResultData.success();
    } catch (Exception e) {
      log.error("邮件发送失败，exception = {}", ExceptionUtils.getStackTrace(e));
      e.printStackTrace();
    }
    return ResultData.fail();
  }

  @Async
  @Override
  public void sendWithAttachmentAsync(EmailSenderReq request) {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    try {
      // true表示支持复杂类型
      helper = new MimeMessageHelper(message, true, "utf-8");
      // 配置邮箱发送人
      helper.setFrom(emailClientConfig.getUsername());
      // 邮件的收件人
      helper.setTo(InternetAddress.parse(String.join(",", request.getToList())));
      // 邮件主题
      helper.setSubject(request.getSubject());
      // 邮件内容
      helper.setText(request.getBodyText());
      // 邮件附件
      for (EmailAttachment attachment : request.getAttachmentList()) {
        // addAttachment的两个参数的意思分别是获取邮件中显示的附件的名称，获取附件的资源
        ByteArrayDataSource ds = new ByteArrayDataSource(
            attachment.getContent(),
            attachment.getContentType()
        );
        helper.addAttachment(attachment.getFileName(), ds);
      }
      javaMailSender.send(helper.getMimeMessage());
      log.info("邮件发送成功");
    } catch (Exception e) {
      log.error("邮件发送失败，exception = {}", ExceptionUtils.getStackTrace(e));
      e.printStackTrace();
    }
  }


}
